package com.demo.mangyThread.threadException.csdn;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @Author: lkz
 * @Title: ExceptionInChildThread3
 * @Description: 在线程内部run()通过try catch捕获异常
 * @Date: 2023/3/28 11:06
 */
@Slf4j
public class ExceptionInChildThread3 implements Runnable{


    @Override
    public void run() {
        try {
            //do something else...
            System.out.println(Thread.currentThread().getName()+":执行");
            throw new RuntimeException("子线程发生了异常...");

        } catch (Exception e) {
            log.error("在线程内部捕获异常", e);
        }
    }

    /**
     * 模拟子线程发生异常
     *
     * @throws InterruptedException
     */
    private static void exceptionThread() throws InterruptedException {
        new Thread(new ExceptionInChildThread3()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
        new Thread(new ExceptionInChildThread3()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
        new Thread(new ExceptionInChildThread3()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
        new Thread(new ExceptionInChildThread3()).start();
        TimeUnit.MILLISECONDS.sleep(200L);
    }

    /**
     * 在主线程尝试通过try catch捕获异常
     */
    private static void catchInMain() {
        try {
            exceptionThread();
        } catch (Exception e) {
            //无法捕获发生在其他线程中的异常
            log.error("捕获到了异常?", e);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExceptionInChildThread3.catchInMain();
    }

    /**
     * 预期：一个线程出现异常之后，其余线程不执行
     * 结果：每个线程内部捕获自己的异常，全部执行
     *
     */


}
